#include <func.h>

#define LOGIN 0
#define REGISTER 1
int makeSalt(char *salt, int maxLen);
//返回用户名
char *userServer(int netfd, MYSQL *db)
{
    //接送用户请求类型（注册or登录） 及 用户名
    int type; // 0-->登录 1-->注册
    int datalen;
    recvn(netfd, &type, sizeof(type));
    recvn(netfd, &datalen, sizeof(datalen));
    char *userName = calloc(datalen, sizeof(char));
    recvn(netfd, userName, datalen);

    //访问数据库寻找用户名
    //需要新建一张userInfo的table
    char sql[256];
    sprintf(sql, "select * from userInfo where username = '%s'", userName);
    int ret = mysql_query(db, sql);
    // MYSQL_ERROR_CHECK(ret, -1, "mysql_query in userServer", db);
    MYSQL_RES *result = mysql_store_result(db);
    int failFlag = 0, num_rows = mysql_num_rows(result);
    if ((num_rows == 0 && type == LOGIN) || (num_rows == 1 && type == REGISTER))
    {
        failFlag = 1;
        printf("%s %s failed!\n", userName, type == LOGIN ? "login" : "register");
        ret = send(netfd, &failFlag, sizeof(failFlag), MSG_NOSIGNAL);
        ERROR_CHECK(ret, -1, "send find uername in database failed in userServer");
        return NULL;
    }
    ret = send(netfd, &failFlag, sizeof(failFlag), MSG_NOSIGNAL);
    ERROR_CHECK(ret, -1, "send find uername in database success in userServer");
    //发送盐值
    char salt[12];
    MYSQL_ROW row;
    if (type == REGISTER)
        makeSalt(salt, sizeof(salt));
    else
    {
        row = mysql_fetch_row(result);
        strncpy(salt, row[2], sizeof(salt));
    }
    send(netfd, salt, sizeof(salt), MSG_NOSIGNAL);
    ERROR_CHECK(ret, -1, "send find salt in database  in userServer");
    //接受密文
    recvn(netfd, &datalen, sizeof(datalen));
    char *ciphertext = malloc(datalen);
    recvn(netfd, ciphertext, datalen);

    //比对或插入密文
    if (type == LOGIN)
    {
        if (strcmp(ciphertext, row[3]) != 0)
        {
            failFlag = 1;
            send(netfd, &failFlag, sizeof(failFlag), MSG_NOSIGNAL);
            ERROR_CHECK(ret, -1, "send  passwd not right success in userServer");
            return NULL;
        }
    }
    else
    {
        sprintf(sql, "insert userInfo (username, salt, passwd) values ('%s', '%s', '%s')", userName, salt, ciphertext);
        ret = mysql_query(db, sql);
        MYSQL_ERROR_CHECK(ret, -1, "mysql_query in userServer", db);
    }
    //发送反馈信息
    send(netfd, &failFlag, sizeof(failFlag), MSG_NOSIGNAL);
    ERROR_CHECK(ret, -1, "send  ");
    free(ciphertext);
    return userName;
}

int makeSalt(char *salt, int maxLen)
{
    strcpy(salt, "$6$");
    srand(time(NULL));
    for (int i = 3; i < maxLen - 1; ++i)
    {
        int flag = rand() % 3;
        switch (flag)
        {
        case 0:
            salt[i] = rand() % 26 + 'a';
            break;
        case 1:
            salt[i] = rand() % 26 + 'A';
            break;
        case 2:
            salt[i] = rand() % 10 + '0';
        default:
            break;
        }
    }
    salt[maxLen] = '$';
    return 0;
}